//
//  KVoAuthLoginVC.swift
//  KVBestMicroblog
//
//  Created by 李康卫 on 16/7/19.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit
import SVProgressHUD

class KVoAuthLoginVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view = webView
        webView.delegate = self
        setupNagationStatus()
        
        //加载登录授权页面
        //拼接get请求
        let URLString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: URLString)
      
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        //提示正在加载
        SVProgressHUD.showWithStatus("正在加载")
        
        //查看是否有值已经保存在沙盒
//        let userInfo = KVUserAccountViewModel.sharedUserAccountViewModel.userAccount
//        print(userInfo?.uid)
        
    }
    // MARK: -  点击事件
    @objc private func fallIn() {
        print(__FUNCTION__)
        //URL: https://api.weibo.com/oauth2/authorize?client_id=2634987363&redirect_uri=http://baidu.com
        //设置自动填充document.getElementById('userId').value='18620144008';document.getElementById('passwd').value='kaiver520'
        let javaScripString: String = "document.getElementById('userId').value='18620144008';document.getElementById('passwd').value='kaiver520'"
        self.webView.stringByEvaluatingJavaScriptFromString(javaScripString)
    }
    @objc private func cancel() {
        SVProgressHUD.dismiss()
        self.navigationController?.dismissViewControllerAnimated(true, completion: { () -> Void in
            
        })
    }
    
    // MARK: - 私有方法
    private func setupNagationStatus() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fallIn")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
    }
    
    
    
    // MARK: - 懒加载
    //加载网页View
    lazy var webView: UIWebView = UIWebView()
}

// MARK: - 网页加载代理方法
extension KVoAuthLoginVC: UIWebViewDelegate {
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //获取字符串
        let URLString = request.URL!.absoluteString
        //http://baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        //http://baidu.com/?code=06ff018839f60d3aac59c6fc76de489a
        
        //如果不是回调的URL直接pass
        if !URLString.hasPrefix(redirect_uri) {
            return true
        } else {
            //取出问号后面的字符串
            let query = request.URL!.query
            let codeString = "code="
            if query!.hasPrefix(codeString) {
                print("success")
                //拿到code值
                let codeNS:NSString = NSString(string: query!)
               let code = codeNS.substringFromIndex(codeString.characters.count)
//                print(code)
                //加载网络数据
                //拿到单例进行网络请求
                KVUserAccountViewModel.sharedUserAccountViewModel.loadAccessToken(code, completedBlock: { (erorr) -> Void in
                    if (erorr != nil) {
                        print("网络请求失败\(erorr)")
                    } else {
                        // MARK: - 回调到百度
                        print("获取数据成功")
                        AppDelegate.setupRootViewController(KVWelcomeVC())
                    }
                })
                

            } else {
                cancel()
            }

        }
        
        return true
    }
    
    
}
